package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xmy.cultivate.entity.BackData;
import com.xmy.cultivate.mapper.BackDataMapper;
import com.xmy.cultivate.service.IBackDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 需要回滚的sql 服务实现类
 * </p>
 *
 * @author min
 * @since 2022-11-28
 */
@Service
public class BackDataServiceImpl extends ServiceImpl<BackDataMapper, BackData> implements IBackDataService {

    @Autowired
    BackDataMapper backDataMapper;

    public boolean insertSql(String sql){
        Integer rs = backDataMapper.insertSql(sql);
        return true;
    }

    public Object selectSql(String sql){
        return backDataMapper.selectSql(sql);
    }

    public boolean updateSql(String sql){
        backDataMapper.updateSql(sql);
        return  true;
    }

    public boolean deleteSql(String sql){
        backDataMapper.deleteSql(sql);
        return true;
    }

    /**
     *
     * @param sourceId 回滚的资源id
     * @param type 回滚类型:默认为1
     * @param backType 回滚类型:0删除作废都回滚,1删除回滚，2作废回滚
     * @return
     */
    @Transactional
    public boolean executeBackData(Long sourceId,Integer type,Integer backType){
        QueryWrapper<BackData> backDataQueryWrapper = new QueryWrapper<>();
        backDataQueryWrapper.eq("source_id",sourceId);
        backDataQueryWrapper.eq("type",type);
        backDataQueryWrapper.eq("back_type",backType);
        backDataQueryWrapper.eq("status",0);

        List<BackData> backDataList = backDataMapper.selectList(backDataQueryWrapper);
        for (BackData backData:backDataList){
            if(StringUtils.isNotBlank(backData.getBackSql())){
                if (backData.getSqlType().equals("insert")){
                    this.insertSql(backData.getBackSql());
                }else if (backData.getSqlType().equals("update")){
                    this.updateSql(backData.getBackSql());
                }else if (backData.getSqlType().equals("delete")){
                    this.deleteSql(backData.getBackSql());
                }else if (backData.getSqlType().equals("select")){
                    this.selectSql(backData.getBackSql());
                }
                backData.setStatus(1);
                backDataMapper.updateById(backData);
            }
        }
        return true;
    }

}
